package pers.zc.activiti.thread.bingfa;

import java.util.concurrent.*;

/**
 * @description 并发运行获取结果
 * @Author Lin FuYuan
 * @date 2020/4/24
 */
public class CompletionServiceDemo {

    public static void main(String[] args) throws InterruptedException {
        // 10个任务  10个线程, 每个任务执行1秒  获取结果只需1秒
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                10,
                10,
                20L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());

        //创建CompletionService对象
        Long start = System.currentTimeMillis();
        CompletionService<Integer> comp = new ExecutorCompletionService<>(executor);
        for (int i = 0; i <10 ; i++) {
            comp.submit(new CallableDemo(i));
        }
        int n = 0;
        for (int i = 0; i < 10; i++) {
            Future<Integer> take = null;
            try {
                take = comp.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Integer integer = null;
            try {
                try {
                    integer = take.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } catch (ExecutionException e) {

            }
            n++;
        }
        System.out.println(n);
        System.out.println(System.currentTimeMillis()-start+"ms");
        executor.shutdown();

    }



}
